/*
 * Copyright (c) 2011-2014, fortiss GmbH.
 * Licensed under the Apache License, Version 2.0.
 *
 * Use, modification and distribution are subject to the terms specified
 * in the accompanying license file LICENSE.txt located at the root directory
 * of this software distribution. A copy is available at
 * http://chromosome.fortiss.org/.
 *
 * This file is part of CHROMOSOME.
 *
 * $Id: loginManagerProcessRequestFunction.c 7837 2014-03-14 12:33:13Z wiesmueller $
 */

/**
 * \file
 *         Source file for function loginManagerProcessRequest in component loginManager.
 *
 * \author
 *         This file has been generated by the CHROMOSOME Modeling Tool (XMT)
 *         (fortiss GmbH).
 */

/******************************************************************************/
/***   Includes                                                             ***/
/******************************************************************************/
#include "xme/core/login/include-gen/loginManagerProcessRequestFunction.h"

#include "xme/core/login/include-gen/loginManagerProcessRequestFunctionWrapper.h"
#include "xme/core/login/include-gen/loginManagerComponent.h"
#include "xme/core/login/include-gen/loginManagerComponentWrapper.h"
#include "xme/core/login/include-gen/loginManagerManifest.h"

#include "xme/core/logUtils.h"

#include "xme/hal/include/mem.h"

// PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_C_INCLUDES) ENABLED START
#include "xme/wp/waypointConfigInfrastructure.h"
#include "xme/core/login/include/loginManager.h"
#include <inttypes.h>
// PROTECTED REGION END

/******************************************************************************/
/***   Definitions                                                          ***/
/******************************************************************************/

// PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_C_DEFINITIONS) ENABLED START

// PROTECTED REGION END

/******************************************************************************/
/***   Variables                                                            ***/
/******************************************************************************/
/**
 * \brief  Variable holding the value of the required output port 'outPnPLoginRequest'.
 *
 * \details If necessary initialize this in the init function.
 *          The value of this variable will be written to the port at the end of
 *          the step function.
 */
static xme_core_topic_login_pnpLoginRequest_t
portOutPnPLoginRequestData;

// PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_C_VARIABLES) ENABLED START

// PROTECTED REGION END

/******************************************************************************/
/***   Prototypes                                                           ***/
/******************************************************************************/

// PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_C_PROTOTYPES) ENABLED START

// PROTECTED REGION END

/******************************************************************************/
/***   Implementation                                                       ***/
/******************************************************************************/
xme_status_t
xme_core_login_loginManagerProcessRequestFunction_init
(
    xme_core_login_loginManagerComponent_config_t* const componentConfig
)
{
    // PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_INITIALIZE_C) ENABLED START

    // Nothing to do

    XME_UNUSED_PARAMETER(componentConfig);

    return XME_STATUS_SUCCESS;

    // PROTECTED REGION END
}

void
xme_core_login_loginManagerProcessRequestFunction_step
(
    xme_core_login_loginManagerComponent_config_t* const componentConfig
)
{
    xme_status_t status[1];
    
    xme_core_topic_login_loginRequest_t portInLoginRequestData; // Required port.
    xme_core_topic_login_pnpLoginRequest_t* portOutPnPLoginRequestDataPtr = &portOutPnPLoginRequestData;
    
    (void)xme_hal_mem_set(&portInLoginRequestData, 0u, sizeof(xme_core_topic_login_loginRequest_t));
    
    status[0] = xme_core_login_loginManagerComponentWrapper_readPortInLoginRequest(&portInLoginRequestData);
    
    {
        // PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_STEP_C) ENABLED START
        xme_status_t returnValue = XME_STATUS_INTERNAL_ERROR;
        xme_com_interface_address_t interfaceAddress;
        char strIPAddress[XME_COM_INTERFACE_IPV4_STRING_BUFFER_SIZE];

        XME_UNUSED_PARAMETER(componentConfig);
        
        XME_CHECK_MSG
        (
            XME_STATUS_SUCCESS == status[0], 
            XME_CHECK_RVAL_VOID, 
            XME_LOG_WARNING, 
            "[LoginManager] Read of port inLoginRequest failed.\n"
        );

        XME_CHECK_MSG
        (
            XME_STATUS_SUCCESS == xme_com_interface_ipv4ToGenericAddress
            (
                portInLoginRequestData.ipAddress,
                portInLoginRequestData.ipAddress >> 8,
                portInLoginRequestData.ipAddress >> 16,
                portInLoginRequestData.ipAddress >> 24,
                xme_hal_net_ntohs(portInLoginRequestData.portAddress),
                &interfaceAddress
            ),
            XME_CHECK_RVAL_VOID,
            XME_LOG_ERROR,
            "[LoginManager] Cannot get the interface address from the login request.\n"
        );

        XME_CHECK_MSG
        (
            XME_STATUS_SUCCESS == xme_com_interface_genericAddressToIPv4String
            (
                &interfaceAddress, strIPAddress, XME_COM_INTERFACE_IPV4_STRING_BUFFER_SIZE
            ),
            XME_CHECK_RVAL_VOID,
            XME_LOG_ERROR,
            "[LoginManager] Error parsing IP address from login request. Login canceled.\n"
        );

        XME_LOG
        (
            XME_LOG_NOTE,
            "[LoginManager] Received a login request from node (guid=%" PRIu64 ", address = %s).\n",
            portInLoginRequestData.guid,
            strIPAddress
        );

        returnValue = xme_core_login_loginManager_loginRequest(&portInLoginRequestData, portOutPnPLoginRequestDataPtr);
        if (XME_STATUS_ALREADY_EXIST == returnValue)
        {
            XME_LOG(XME_LOG_WARNING,
                "[LoginManager] Node (guid = %" PRIu64 ", address = %s) already logged into the system with node ID = %d. Ignoring login request.\n",
                portInLoginRequestData.guid,
                strIPAddress,
                portOutPnPLoginRequestDataPtr->nodeId
            );
        }
        XME_CHECK_MSG
        (
            XME_STATUS_SUCCESS == returnValue,
            XME_CHECK_RVAL_VOID,
            XME_LOG_ERROR,
            "[LoginManager] Internal error during login of node (guid = %" PRIu64 ", address = %s). Login canceled\n",
            portInLoginRequestData.guid,
            strIPAddress
        );

        XME_CHECK_MSG_REC
        (
            XME_STATUS_SUCCESS == xme_wp_wci_addConfig(portInLoginRequestData.ipAddress, portInLoginRequestData.portAddress,
                                                           (xme_core_channelId_t)XME_CORE_TOPIC_LOGIN_LOGINRESPONSE, XME_CORE_TOPIC_LOGIN_LOGINRESPONSE),
            XME_CHECK_RVAL_VOID,
            {
                xme_status_t status = XME_STATUS_INTERNAL_ERROR;

                status = xme_core_directory_nodeRegistryController_deregisterNode(portOutPnPLoginRequestDataPtr->nodeId);
                if (XME_STATUS_SUCCESS != status)
                {
                    XME_LOG(XME_LOG_ERROR, "[LoginManager] Error deregistering node with node ID %d after erroneous login.\n", portOutPnPLoginRequestDataPtr->nodeId);
                }
            },
            XME_LOG_ERROR,
            "[LoginManager] Addition of outgoing communication path for login response to node (guid = %" PRIu64 ", address = %s) failed. Login not possible.\n", portInLoginRequestData.guid, strIPAddress
        );

        XME_LOG
        (
            XME_LOG_NOTE,
            "[LoginManager] New node logged in with node ID = %d (guid = %" PRIu64 ", address = %s).\n",
            portOutPnPLoginRequestDataPtr->nodeId,
            portInLoginRequestData.guid,
            strIPAddress
        );

        XME_LOG
        (
            XME_LOG_DEBUG,
            "[LoginManager] Sending a PnP Login Request for node %d. \n",
            portOutPnPLoginRequestDataPtr->nodeId
        );

        // PROTECTED REGION END
    }
    
    status[0] = xme_core_login_loginManagerComponentWrapper_writePortOutPnPLoginRequest(portOutPnPLoginRequestDataPtr);
    
    {
        // PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_STEP_2_C) ENABLED START

        XME_CHECK_MSG
        (
            XME_STATUS_SUCCESS == status[0],
            XME_CHECK_RVAL_VOID,
            XME_LOG_WARNING,
            "The write port operation failed."
        );

        // PROTECTED REGION END
    }
}

void
xme_core_login_loginManagerProcessRequestFunction_fini
(
    xme_core_login_loginManagerComponent_config_t* const componentConfig
)
{
    // PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_TERMINATE_C) ENABLED START

    // Nothing to do

    XME_UNUSED_PARAMETER(componentConfig);

    // PROTECTED REGION END
}

// PROTECTED REGION ID(XME_CORE_LOGIN_LOGINMANAGERPROCESSREQUESTFUNCTION_IMPLEMENTATION_C) ENABLED START

// PROTECTED REGION END
